package cl.foursoft.sensordaemon.controllers;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cl.foursoft.sensordaemon.dao.facade.FacadeArchivo;
import cl.foursoft.sensordaemon.dao.implementation.DBMannager;
import cl.foursoft.sensordaemon.domain.Archivo;
import cl.foursoft.sensordaemon.domain.UploadedFile;
import cl.foursoft.sensordaemon.utils.FileValidator;
import cl.foursoft.sensordaemon.utils.UtilImage;

@Controller
public class UploadController {

//	@Autowired
//	private ServletContext context;

//	@Autowired

//	
	@Autowired  
	private FileValidator fileValidator;  

	@RequestMapping("/fileUploadForm")  
	public ModelAndView getUploadForm(
			@ModelAttribute("uploadedFile") UploadedFile uploadedFile,  
			BindingResult result
			) {  
		return new ModelAndView("archivo/uploadForm");  
	}  

	@RequestMapping("/fileUpload")  
	public ModelAndView fileUploaded(  
			@ModelAttribute("uploadedFile") UploadedFile uploadedFile,  
			BindingResult result
			) {  
		InputStream inputStream = null;  
		OutputStream outputStream = null;  

		MultipartFile file = uploadedFile.getFile();  
		fileValidator.validate(uploadedFile, result);  

		String fileName = file.getOriginalFilename();  

		if (result.hasErrors()) {  
			return new ModelAndView("archivo/uploadForm");  
		}  

		try {  
			inputStream = file.getInputStream();  

			File newFile = new File("D:/" + fileName);  
			if (!newFile.exists()) {  
				newFile.createNewFile();  
			}  
			outputStream = new FileOutputStream(newFile);  
			int read = 0;  
			byte[] bytes = new byte[1024];  

			while ((read = inputStream.read(bytes)) != -1) {  
				outputStream.write(bytes, 0, read);  
			}  
			outputStream.close();
		} catch (IOException e) {   
			e.printStackTrace();  
		}  

		return new ModelAndView("archivo/showFile", "message", fileName);  
	}  


	@RequestMapping(value="/upload/file", method=RequestMethod.POST )
	@ResponseBody
	public Boolean subirArchivos(@RequestParam(value = "file", required = false) MultipartFile image,
			@RequestParam(value = "name") String name,
			@RequestParam(value = "final") String nameFinal
			) throws IOException{
		Boolean resp = true;
		Archivo archivo = null;

		try{

			//GUARDAR IMAGEN
			archivo = new Archivo();
			archivo.setNombreArchivo(name);

			
			//GUARDAR FILE			     
			File directorio = new File(UtilImage.PATH);
			if(!directorio.exists()){
				directorio.mkdirs();
			}

			String ext = UtilImage.getExtension(name);
			if(!ext.equals("")) 
				ext = "."+ext;

			String absolutePath = UtilImage.PATH + File.separator + nameFinal;// archivo.getNombreArchivo();
			archivo.setNombreArchivo(absolutePath);
			
			
			
			File file = new File(absolutePath);
			FileUtils.writeByteArrayToFile(file, image.getBytes());
			
			//guardamos el archivo en la base de datos (ya sea con JPA o SQL)
			Connection c =  DBMannager.getConnection();
			FacadeArchivo facadeArchivo = new FacadeArchivo();
			if(facadeArchivo.guardarArchivo(archivo, c) != null)
				DBMannager.close(c, true);
			else
			{
				DBMannager.close(c, false);
				resp = false;
			}

		}catch(Exception e){
			e.printStackTrace();
			archivo = null;
			resp = false;
		}

		return resp;
	}

	@RequestMapping(value="/upload/images", method=RequestMethod.POST )
	@ResponseBody
	public Boolean subirImagenes(@RequestParam(value = "images", required = false) MultipartFile[] images,
			@RequestParam(value = "names") String [] names
			) throws IOException{

		return true;
	}

	@RequestMapping(value = "/get/file/{id}", method = RequestMethod.GET)
	@ResponseBody
	public FileSystemResource getFile(@PathVariable("id") String id) {
		String imageRootPath = UtilImage.PATH + File.separator +id+".jpg";
		return new FileSystemResource(imageRootPath); 
	}

//	@RequestMapping(value = "/get/image/{id}", method = RequestMethod.GET)
//	@ResponseBody
//	public void getImage(@PathVariable("id") String id,  HttpServletResponse response) {
//		try {
//			// get your file as InputStream
//			String imageRootPath = UtilImage.PATH + File.separator +id+".jpg";
//			File file = new File(imageRootPath);
//
//			String mimetype = context.getMimeType(imageRootPath);
//			response.setContentType( (mimetype != null) ? mimetype : "application/octet-stream" );
//			response.setContentLength( (int)file.length() );
//			response.setHeader( "Content-Disposition", "inline; filename=\"" + "" + "\"" );
//
//			//response.setContentType("image/jpg");		    	
//			response.setContentLength((int)file.length());
//			FileInputStream in = new FileInputStream(file);
//			// copy it to response's OutputStream
//			IOUtils.copy(in, response.getOutputStream());
//			response.flushBuffer();
//		} catch (IOException ex) {	
//			System.out.println("getImage " + ex.getCause());
//			//		        throw new RuntimeException("IOError writing file to output stream");
//		}
//	}
}
